package Thread;

import java.util.concurrent.PriorityBlockingQueue;

/**
 * 自己实现一个计时器
 * 1.需要一个数据结构放任务
 * 2.有一个线程扫描任务
 */
class MyTask implements Comparable<MyTask> {
    private Runnable runnable;
    private long time;

    public MyTask(Runnable task, long time) {
        this.time = time;
        this.runnable= task;
    }

    public long getTime() {
        return time;
    }
    public void run() {
        runnable.run();
    }

    @Override
    public int compareTo(MyTask o) {
        return (int) (this.time - o.time);
    }

}

class MyTimer{
    private Thread t = null;
    private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();

    public MyTimer() {
        t = new Thread(()->{
            while (true) {
                try {
                    System.out.println("this2:"+this);
                    synchronized (this) {
                        MyTask task = queue.take();
                        long nowTime = System.currentTimeMillis();
                        if (nowTime >= task.getTime()) {
                            task.run();
                        } else {
                            queue.put(task);
                            this.wait(task.getTime()-nowTime);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }

    public void schedule(Runnable runnable, long time) {
        MyTask task = new MyTask(runnable,System.currentTimeMillis()+time);
        queue.put(task);
        System.out.println("this2:"+this);
        synchronized (this) {
            this.notify();
        }
    }
}

public class ThreadDemo18 {

    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1");
            }
        },1000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2");
            }
        },2000);
    }

}
